/*
 * @Author: Zeng Hugh
 * @Date: 2020-01-03 13:32:50
 * @Last Modified by: Zeng Hugh
 * @Last Modified time: 2020-01-03 15:32:57
 */

using RuleJudge.RuleData;
using SLANCommon;
using SLANCommon.Enum;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Windows.Media;

namespace RuleJudge.Judge
{
    public class MTB_RIF : BaseJudge
    {
        /// <summary>
        /// 构造函数，需要定义项目类型，管，通道信息
        /// </summary>

        #region 定义判读中常量Cutoff,高中低、ΔCt、初始荧光信号强度范围,终点荧光限号强度范围
        //定义常量：内参阳性判断参考值，结核IS6110阳性判断参考值
        public const double IPC_Positive_Cutoff = 35.00;  //内参IPC阳性参考值
        public const double MTB_Positive_Cutoff = 31.98;  //IS6110阳性参考值
        public const double RIF_Positive_Cutoff = 35.00;  //rpoB阳性参考值,用于阳性质控判断
        public const double MTB_VeryLow_Cutoff = 28.00;
        public const double MTB_Low_Cutoff = 24.00;       //结核浓度非常低参考值，仅作为中间结果展示
        public const double MTB_Middle_Cutoff = 18.00;
        public const double MTB_High_Cutoff = 12.00;
        public const double RIF_Low = 31.00;
        public const double RIF_Middle = 25.00;
        public const double RIF_High = 19.00;

        //定义常量：根据IS6110结核分枝杆菌浓度非常低
        //根据临床数据分析确定非常低标准为IS6110的Ct值>24(2021.06.11 吴贵银、洪冉)
        //public const double MTB_Very_Low = 24.00;

        //定义常量：5条探针各自突变判断参考值
        public const double ProbeA_Mutation = 2.09;  //ΔCt_ProbeA : 510, 511, 512
        public const double ProbeB_Mutation = 2.00;  //ΔCt_ProbeB : 513，515，516
        public const double ProbeC_Mutation = 2.93;  //ΔCt_ProbeC : 522，517&518Del
        public const double ProbeD_Mutation = 3.81;  //ΔCt_ProbeD : 526
        public const double ProbeE_Mutation = 3.15;  //ΔCt_ProbeE : 531, 533
        #endregion

        public MTB_RIF()
        {
            Type = EProjectType.AQ;
            TubesNo = new List<int>() { 1, 1, 1, 1, 1, 2, 2, 2, 2, 2 };
            ChannelsNo = new List<int>() { 1, 2, 3, 4, 5, 1, 2, 3 ,4, 5};
        }

        /// <summary>
        /// 判断逻辑
        /// </summary>
        /// <param name="samples">样本列表</param>
        /// <returns>非空：SLAN会弹出内容信息框，进行提示</returns>
        public override string Judge(List<Sample> samples)
        {
            //在结果判断之前，先检查是否有需要判断的样本
            if (samples.Count == 0) return "无判断样本！";

            int FAM = 0;
            int VIC = 1;
            int ROX = 2;
            int CY5 = 3;
            int Quasar705 = 4;
            int Negative_Num = 0;
            int Positive_Num = 0;
            bool Negative_Pass = false;
            bool Leak_Negative_Control = false;
            bool Positive_Pass = false;
            bool Leak_Positive_Control = false;

            /* ****************************************************************************************************************
             * 阴性质控(对照)的判读标准：（1）第二孔FAM通道Ct大于MTB_Positive_Cutoff，第一二孔CY5通道Ct大于RIF_Positive_Cutoff；****
             * ************************（2）第一二孔Quasar705通道Ct小于等于IPC_Positive_Cutoff **********************************
             * ****************************************************************************************************************
             */
            #region 阴性质控(对照)的判读
            List<Sample> NegativeList = samples.Where(s => s.Type == SampleType.Negative).ToList();
            if(NegativeList.Count != 0)  //判断是否存在阴性质控
            {
                foreach (Sample sample in NegativeList)
                {
                    if (sample.Tubes[1].Targets[FAM].Result.Ct > MTB_Positive_Cutoff &&
                        sample.Tubes[0].Targets[CY5].Result.Ct > RIF_Positive_Cutoff &&
                        sample.Tubes[1].Targets[CY5].Result.Ct > RIF_Positive_Cutoff &&
                        sample.Tubes[0].Targets[Quasar705].Result.Ct <= IPC_Positive_Cutoff &&
                        sample.Tubes[1].Targets[Quasar705].Result.Ct <= IPC_Positive_Cutoff)
                    {
                        sample.Conclusion.Add(new Conclusion() { Content = "阴性质控：符合要求", Color=Colors.Green });
                        Negative_Num = Negative_Num + 1;
                    }
                    else
                    {
                        sample.Conclusion.Add(new Conclusion() { Content = "阴性质控：不符合要求", Color=Colors.Red });
                    }
                }
                if(NegativeList.Count == Negative_Num)
                {
                    Negative_Pass = true;
                }
            }
            // 一次实验中未设置阴性指控则给予提示
            else
            {
                Negative_Pass = true;
                Leak_Negative_Control = true;
            }
            #endregion

            /* ****************************************************************************************************************
             * 阳性质控判读标准：（1）各通道均有扩增曲线 **************************************************************************
             * ****************************************************************************************************************
             */
            #region 阳性质控(对照)的判读
            List<Sample> PositiveList = samples.Where(s => s.Type == SampleType.HighPositive).ToList();
            if(PositiveList.Count != 0)  //判断是否存在阳性质控
            {
                foreach (Sample sample in PositiveList)
                {
                    #region 判断各通道Ct值是否符合要求
                    if(    sample.Tubes[0].Targets[FAM].Result.Ct <= RIF_Positive_Cutoff
                        && sample.Tubes[0].Targets[VIC].Result.Ct <= RIF_Positive_Cutoff
                        && sample.Tubes[0].Targets[ROX].Result.Ct <= RIF_Positive_Cutoff
                        && sample.Tubes[0].Targets[CY5].Result.Ct <= RIF_Positive_Cutoff
                     // && sample.Tubes[0].Targets[Quasar705].Result.Ct <= IPC_Positive_Cutoff
                        && sample.Tubes[1].Targets[FAM].Result.Ct <= MTB_Positive_Cutoff
                        && sample.Tubes[1].Targets[VIC].Result.Ct <= RIF_Positive_Cutoff
                        && sample.Tubes[1].Targets[ROX].Result.Ct <= RIF_Positive_Cutoff
                        && sample.Tubes[1].Targets[CY5].Result.Ct <= RIF_Positive_Cutoff
                     // && sample.Tubes[1].Targets[Quasar705].Result.Ct <= IPC_Positive_Cutoff
                        )
                    {
                        sample.Conclusion.Add(new Conclusion() { Content = "阳性质控：符合要求", Color=Colors.Green });
                        sample.CustomResults.Add(new CustomResult() { Name = "内参质控", Content = "/" });
                        Positive_Num = Positive_Num + 1;
                    }
                    else
                    {
                        sample.Conclusion.Add(new Conclusion() { Content = "阳性质控：不符合要求", Color=Colors.Red  });
                        sample.CustomResults.Add(new CustomResult() { Name = "内参质控", Content = "/" });
                    }
                    #endregion
                }
                if(PositiveList.Count == Positive_Num)
                {
                	Positive_Pass = true;
                }
            }
            //在一次实验中未设置阳性质控，则给与提示
            else
            {
            	Positive_Pass = true;
            	Leak_Positive_Control = true;
            }
            #endregion

            /* ****************************************************************************************************************
             * 待测（未知）样本结果判读标准：（1）阴阳性质控全部合格，按照规定进行结核分枝杆菌和利福平耐药判读；************************
             * ***************************（2）否则，直接结束判读，提示阴阳性质控不合格！******************************************
             * ****************************************************************************************************************
             */
            #region 待测样本结果判读
            List<Sample> UnknownList = samples.Where(s => s.Type == SampleType.Unknown).ToList();   //取出所有“待测样本”
            if(UnknownList.Count != 0)
            {
                foreach (Sample sample in UnknownList)
                {
                    /* ****************************************************************************************************************
                     * 获取内参和IS6110的Ct值，判断内参是否符合要求 *******************************************************************
                     * 样品处理质控IPC检查：(1) 两孔内参IPC扩增正常，Ct <= IPC_Positive_Cutoff; ***************************************
                     * *********************(2) IS6110 扩增正常，Ct <= MTB_Positive_Cutoff ********************************************
                     * ****************************************************************************************************************
                    */
                    #region
                    bool IPC_Positive = false;
                    if (sample.Tubes[0].Targets[Quasar705].Result.Ct <= IPC_Positive_Cutoff && sample.Tubes[1].Targets[Quasar705].Result.Ct <= IPC_Positive_Cutoff ||
                        sample.Tubes[1].Targets[FAM].Result.Ct <= MTB_Positive_Cutoff)
                    {
                        IPC_Positive = true;
                        sample.CustomResults.Add(new CustomResult() { Name = "内参质控", Content = "合格", Color=Colors.Green });
                    }
                    else // 质控IPC受到抑制，或不符合要求
                    {
                        sample.CustomResults.Add(new CustomResult() { Name = "内参质控", Content = "不合格", Color=Colors.Red, BackgroundColor=Colors.Yellow});
                        sample.Conclusion.Add(new Conclusion() { Content = "结核分枝杆菌检测结果：无结果", Color=Colors.Red, BackgroundColor=Colors.Yellow});
                        sample.Conclusion.Add(new Conclusion() { Content = "\n" + "利福平耐药检测结果：无结果", Color=Colors.Red, BackgroundColor=Colors.Yellow});
                    }
                    #endregion

                    /* ****************************************************************************************************************
                     * 根据结核分枝杆菌IS6110的Ct值，判断结核分枝杆菌是否检出 *************************************************************
                     * 获取IS6110和rpoB的Ct值,给出中间结论（高，中，低，极低）*************************************************************
                     * Ct值（IS6110）≤ MTB_Cutoff，报告“结核分枝杆菌检测结果MTB：检出”；否则报告“结核分枝杆菌检测结果MTB：未检出”*************
                     * ****************************************************************************************************************
                     */
                    #region
                    if (IPC_Positive)
                    {
                        bool hasNext = false;
                        // 根据结核分枝杆菌IS6110的Ct值，判断结核分枝杆菌是否检出
                        if (sample.Tubes[1].Targets[FAM].Result.Ct <= MTB_Positive_Cutoff)
                        {
                            hasNext = true;
                            sample.Conclusion.Add(new Conclusion() { Content = "结核分枝杆菌检测结果：检出", Color=Colors.Red });
                            if(sample.Tubes[1].Targets[FAM].Result.Ct > MTB_VeryLow_Cutoff)
                            {
                                sample.Tubes[1].Targets[FAM].Conclusion.Add(new Conclusion { Content = "检出（极低）", Color = Colors.Red });
                            }
                            else if((sample.Tubes[1].Targets[FAM].Result.Ct <= MTB_VeryLow_Cutoff) && (sample.Tubes[1].Targets[FAM].Result.Ct > MTB_Low_Cutoff))
                            {
                                sample.Tubes[1].Targets[FAM].Conclusion.Add(new Conclusion { Content = "检出（非常低）", Color = Colors.Red });
                            }
                            else if((sample.Tubes[1].Targets[FAM].Result.Ct <= MTB_Low_Cutoff) && (sample.Tubes[1].Targets[FAM].Result.Ct > MTB_Middle_Cutoff))
                            {
                                sample.Tubes[1].Targets[FAM].Conclusion.Add(new Conclusion { Content = "检出（低）", Color = Colors.Red });
                            }
                            else if((sample.Tubes[1].Targets[FAM].Result.Ct <= MTB_Middle_Cutoff) && (sample.Tubes[1].Targets[FAM].Result.Ct > MTB_High_Cutoff))
                            {
                                sample.Tubes[1].Targets[FAM].Conclusion.Add(new Conclusion { Content = "检出（中）", Color = Colors.Red });
                            }
                            else
                            {
                                sample.Tubes[1].Targets[FAM].Conclusion.Add(new Conclusion { Content = "检出（高）", Color = Colors.Red });
                            }
                        }
                        else
                        {
                            //突变探针靶标中间结论
                            sample.Tubes[0].Targets[FAM].Conclusion.Add(new Conclusion { Content = "ΔCt A: 0.00", Color = Colors.Green, BackgroundColor = Colors.LightYellow });
                            sample.Tubes[0].Targets[VIC].Conclusion.Add(new Conclusion { Content = "ΔCt C: 0.00", Color = Colors.Green, BackgroundColor = Colors.LightYellow });
                            sample.Tubes[0].Targets[ROX].Conclusion.Add(new Conclusion { Content = "ΔCt E: 0.00", Color = Colors.Green, BackgroundColor = Colors.LightYellow });
                            sample.Tubes[1].Targets[VIC].Conclusion.Add(new Conclusion { Content = "ΔCt B: 0.00", Color = Colors.Green, BackgroundColor = Colors.LightYellow });
                            sample.Tubes[1].Targets[ROX].Conclusion.Add(new Conclusion { Content = "ΔCt D: 0.00", Color = Colors.Green, BackgroundColor = Colors.LightYellow });
                            //样本检测结论
                            sample.Conclusion.Add(new Conclusion() { Content = "结核分枝杆菌检测结果：未检出", Color=Colors.Green });
                            sample.Tubes[1].Targets[FAM].Conclusion.Add(new Conclusion { Content = "阴性", Color = Colors.Green });
                        }

                        // 计算ΔCt判断是否存在rpoB基因利福平耐药突变,NoCt就是double无穷大，MTB浓度过低时利福平耐药判读结果不可靠！
                        // NoCt就是double无穷大,计算ΔCt时替换成40
                        double Ct_Probe_A = double.IsInfinity(sample.Tubes[0].Targets[FAM].Result.Ct) == true ? 40 : sample.Tubes[0].Targets[FAM].Result.Ct;
                        double Ct_Probe_C = double.IsInfinity(sample.Tubes[0].Targets[VIC].Result.Ct) == true ? 40 : sample.Tubes[0].Targets[VIC].Result.Ct;
                        double Ct_Probe_E = double.IsInfinity(sample.Tubes[0].Targets[ROX].Result.Ct) == true ? 40 : sample.Tubes[0].Targets[ROX].Result.Ct;
                        double Ct_rpoB_1 = double.IsInfinity(sample.Tubes[0].Targets[CY5].Result.Ct) == true ? 40 : sample.Tubes[0].Targets[CY5].Result.Ct;
                        double Ct_Probe_B = double.IsInfinity(sample.Tubes[1].Targets[VIC].Result.Ct) == true ? 40 : sample.Tubes[1].Targets[VIC].Result.Ct;
                        double Ct_Probe_D = double.IsInfinity(sample.Tubes[1].Targets[ROX].Result.Ct) == true ? 40 : sample.Tubes[1].Targets[ROX].Result.Ct;
                        double Ct_rpoB_2 = double.IsInfinity(sample.Tubes[1].Targets[CY5].Result.Ct) == true ? 40 : sample.Tubes[1].Targets[CY5].Result.Ct;
                        //计算各突变探针ΔCt值
                        double Delta_CtA = Ct_Probe_A - Ct_rpoB_1;
                        double Delta_CtC = Ct_Probe_C - Ct_rpoB_1;
                        double Delta_CtE = Ct_Probe_E - Ct_rpoB_1;
                        double Delta_CtB = Ct_Probe_B - Ct_rpoB_2;
                        double Delta_CtD = Ct_Probe_D - Ct_rpoB_2;
                        if (hasNext)
                        {
                            // 若任意反应管rpoB的Ct值大于31就判为敏感
                            if (Ct_rpoB_1 > 31 && Ct_rpoB_2 >31)
                            {
                                //突变探针靶标中间结论
                                sample.Tubes[0].Targets[FAM].Conclusion.Add(new Conclusion { Content = "ΔCt A: 0.00", Color = Colors.Green, BackgroundColor = Colors.LightYellow });
                                sample.Tubes[0].Targets[VIC].Conclusion.Add(new Conclusion { Content = "ΔCt C: 0.00", Color = Colors.Green, BackgroundColor = Colors.LightYellow });
                                sample.Tubes[0].Targets[ROX].Conclusion.Add(new Conclusion { Content = "ΔCt E: 0.00", Color = Colors.Green, BackgroundColor = Colors.LightYellow });
                                sample.Tubes[1].Targets[VIC].Conclusion.Add(new Conclusion { Content = "ΔCt B: 0.00", Color = Colors.Green, BackgroundColor = Colors.LightYellow });
                                sample.Tubes[1].Targets[ROX].Conclusion.Add(new Conclusion { Content = "ΔCt D: 0.00", Color = Colors.Green, BackgroundColor = Colors.LightYellow });
                                // 样本检测结论——利福平
                                sample.Conclusion.Add(new Conclusion() { Content = "\n利福平耐药检测结果：敏感", Color = Colors.Green });
                            }
                            else
                            {
                                // A管FAM通道中间结论
                                sample.Tubes[0].Targets[FAM].Conclusion.Add(new Conclusion
                                {
                                    Content = "ΔCt A: " + Delta_CtA.ToString("#0.00"),
                                    Color = Delta_CtA >= ProbeA_Mutation ? Colors.Red : Colors.Green,
                                    BackgroundColor = Delta_CtA >= ProbeA_Mutation ? Colors.LightYellow : Colors.LightYellow,
                                });
                                // A管VIC通道中间结论
                                sample.Tubes[0].Targets[VIC].Conclusion.Add(new Conclusion
                                {
                                    Content = "ΔCt C: " + Delta_CtC.ToString("#0.00"),
                                    Color = Delta_CtC >= ProbeC_Mutation ? Colors.Red : Colors.Green,
                                    BackgroundColor = Delta_CtC >= ProbeC_Mutation ? Colors.LightYellow : Colors.LightYellow,
                                });
                                // A管ROX通道中间结论
                                sample.Tubes[0].Targets[ROX].Conclusion.Add(new Conclusion
                                {
                                    Content = "ΔCt E: " + Delta_CtE.ToString("#0.00"),
                                    Color = Delta_CtE >= ProbeE_Mutation ? Colors.Red : Colors.Green,
                                    BackgroundColor = Delta_CtE >= ProbeE_Mutation ? Colors.LightYellow : Colors.LightYellow,
                                });
                                // B管VIC通道中间结论
                                sample.Tubes[1].Targets[VIC].Conclusion.Add(new Conclusion
                                {
                                    Content = "ΔCt B: " + Delta_CtB.ToString("#0.00"),
                                    Color = Delta_CtB >= ProbeB_Mutation ? Colors.Red : Colors.Green,
                                    BackgroundColor = Delta_CtB >= ProbeB_Mutation ? Colors.LightYellow : Colors.LightYellow,
                                });
                                // B管ROX通道中间结论
                                sample.Tubes[1].Targets[ROX].Conclusion.Add(new Conclusion
                                {
                                    Content = "ΔCt D: " + Delta_CtD.ToString("#0.00"),
                                    Color = Delta_CtD >= ProbeD_Mutation ? Colors.Red : Colors.Green,
                                    BackgroundColor = Delta_CtD >= ProbeD_Mutation ? Colors.LightYellow : Colors.LightYellow,
                                });
                                // 满足任意一条，则报告“利福平耐药突变检测结果RIF：耐药”，否则“利福平耐药突变检测结果RIF：敏感”。
                                if (Delta_CtA >= ProbeA_Mutation || Delta_CtB >= ProbeB_Mutation || Delta_CtC >= ProbeC_Mutation || Delta_CtD >= ProbeD_Mutation || Delta_CtE >= ProbeE_Mutation)
                                {
                                    sample.Conclusion.Add(new Conclusion() { Content = "\n利福平耐药检测结果：耐药", Color = Colors.Red });
                                }
                                else
                                {
                                    sample.Conclusion.Add(new Conclusion() { Content = "\n利福平耐药检测结果：敏感", Color = Colors.Green });
                                }
                            }
                        }
                    }
                    #endregion
                }
            }
            #endregion

            /* ****************************************************************************************************************
             * 实验中未设置阴阳性质控不影响判读，仅给出弹窗提醒缺少质控 ************************************************************
             * 阴阳性质控不合格的，则给出提醒，但仍然进行判读 *********************************************************************
             * ****************************************************************************************************************
             */
            #region 质控异常或缺失提示
            if(!Negative_Pass || !Positive_Pass)
            {
                MessageBox.Show("一个或多个阴阳性质控不符合要求！是否忽略？", "质控提示", MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
            }
            if(Leak_Negative_Control || Leak_Positive_Control)
            {
                MessageBox.Show("实验缺少阴性质控或阳性质控！是否忽略？", "质控提示", MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
            }
            #endregion

            return string.Empty;
        }
    }
}